package com.zjpavt.client.hal;

import com.zjpavt.client.nativemethod.JnIMethod;
import com.zjpavt.client.util.LoggerUtil;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import sun.nio.ch.ThreadPool;

import java.util.concurrent.*;

/**
 * 蜂鸣器控制
 *
 * @author zyc
 */
@Slf4j
public class Buzzer {
    public static final Executor threadPool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(4), new DefaultThreadFactory("Buzzer"));


    /**
     * 网线断线时的蜂鸣器
     * 开关门报警
     */
    public synchronized static void buzzerFive() {
        try {
            for (int i = 0; i < 5; i++) {
                JnIMethod.Buzzer(1);
                Thread.sleep(Integer.valueOf(1000));
                JnIMethod.Buzzer(0);
                Thread.sleep(Integer.valueOf(1000));
            }
        } catch (InterruptedException e) {
            log.error(LoggerUtil.convertException2String(e));
        }
        finally {
            JnIMethod.Buzzer(0);
        }
    }


    /**
     * 网线连接 提示
     */
    public synchronized static void buzzerTwo() {
        try {
            for (int i = 0; i < 2; i++) {
                JnIMethod.Buzzer(1);
                Thread.sleep(Integer.valueOf(300));
                JnIMethod.Buzzer(0);
                Thread.sleep(Integer.valueOf(300));
            }
        } catch (InterruptedException e) {
            log.error(LoggerUtil.convertException2String(e));
        }
        finally {
            JnIMethod.Buzzer(0);
        }
    }

    /**
     * @param period    周期，蜂鸣器开启关闭次数
     * @param openTime  开启时间，ms
     * @param closeTime 关闭时间，ms
     */
    public synchronized static void buzzer(int period, int openTime, int closeTime) {
        log.info("buzzer " + openTime + "openTime");
        try {
            for (int i = 0; i < period; i++) {
                JnIMethod.Buzzer(1);
                Thread.sleep(Integer.valueOf(openTime));
                JnIMethod.Buzzer(0);
                Thread.sleep(Integer.valueOf(closeTime));
            }
        } catch (InterruptedException e) {
            log.error(LoggerUtil.convertException2String(e));
        }
        finally {
            JnIMethod.Buzzer(0);
        }
    }

    public synchronized static void buzzer(int period, int openTime, int closeTime, boolean returnNow) {
        if (returnNow) {
            threadPool.execute(() -> buzzer(period, openTime, closeTime));
        } else {
            buzzer(period, openTime, closeTime);
        }
    }
}
